package com.keson.guard.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;

import java.util.List;

public class UICheckUtil {

    /**
     * 检测一个android程序是否在运行
     * @param context
     * @param packageName
     * @return
     * <uses-permission android:name="android.permission.REAL_GET_TASKS"/>
     */
    public static  boolean isServiceStarted(Context context,String packageName) {
//        if(Build.MODEL.indexOf("100c")>-1){
            return !CmdUtil.execRootCmd("ps -e |grep "+packageName).equals("");
//        }else{
//            //<uses-permission android:name="android.permission.GET_TASKS"/>
//            //https://crazier9527.iteye.com/blog/1476134
//            boolean isStarted =false;
//            try {
//                ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
//                int intGetTastCounter = 1000;
//                List<ActivityManager.RunningServiceInfo> mRunningService = mActivityManager.getRunningServices(intGetTastCounter );
//                for (ActivityManager.RunningServiceInfo amService : mRunningService) {
//                    if(0 == amService.service.getPackageName().compareTo(packageName)) {
//                        isStarted = true;
//                        break;
//                    }
//                }
//            }
//            catch(SecurityException e) {
//                e.printStackTrace();
//            }
//            return isStarted;
//        }
    }

    /**
     * 判断程序是否安装
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isApkInstalled(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
//        try {
//            if(Build.MODEL.indexOf("100c")>-1){
                return !CmdUtil.execRootCmd("pm list package | grep "+packageName).equals("");
//            }else{
//                ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
//                return true;
//            }
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//            return false;
//        }
    }
}
